package com.atguigu.yygh.user.api;

import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.sms.SMSUtils;
import com.atguigu.yygh.common.sms.ValidateCodeUtils;
import com.atguigu.yygh.common.utils.AuthContextHolder;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserInfoApiController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 腾讯云发送短信
     *
     * @param phone
     * @return
     */
    @ApiOperation(value = "会员登录")
    @PostMapping("/sendMsg/{phone}")
    public Result sendMsg(@PathVariable String phone) {
        //判断输入手机号是否合法
        if (StringUtils.isEmpty(phone) || phone.length() != 11)
            return Result.fail().message("请输入合法的手机号");
        //手机号为Key Value为验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);

        if (!StringUtils.isEmpty(codeInRedis)) return Result.ok(); //对应的就是code
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("code={}", code);
        //调用云短信服务
        Boolean flag = SMSUtils.sendMessage(phone, code);
        //发送成功 验证码保存到Redis设置有效期为五分钟
        if (true) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.ok();
        } else return Result.fail().message("短信发送失败！");
    }

    //用户手机号登录接口
//    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request) {
        //loginVo.setIp(IpUtil.getIpAddr(request));
        Map<String, Object> info = userInfoService.loginUser(loginVo);
        return Result.ok(info);
    }

    //用户认证接口
    @PostMapping("auth/userAuth")
    public Result userAuth(@RequestBody UserAuthVo userAuthVo, HttpServletRequest request) {
        //传递两个参数，第一个参数用户id，第二个参数认证数据vo对象
        userInfoService.userAuth(AuthContextHolder.getUserId(request),userAuthVo);
        return Result.ok();
    }

    //获取用户id信息接口
    @GetMapping("auth/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        Long userId = AuthContextHolder.getUserId(request);
        UserInfo userInfo = userInfoService.getById(userId);
        return Result.ok(userInfo);
    }
}
